#include "characterspecialsform.h"
#include "ui_characterspecialsform.h"
#include "characterspecialdelegate.h"


#include <QItemSelectionModel>
#include <QVBoxLayout>
#include <QCheckBox>
#include <QTimer>


CharacterSpecialsForm::CharacterSpecialsForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CharacterSpecialsForm)
{
    ui->setupUi(this);

    // button group
    m_checkboxes = new QButtonGroup(ui->tabCharacterClasses);
    m_checkboxes->setExclusive(false);
    connect(m_checkboxes, SIGNAL(buttonClicked(int)), this, SLOT(onCheckBoxClicked(int)));

    // source models
    m_specialTable = new SpecialTableModel(this);
    m_specialsSelect = new SpecialsSelectModel(this);


    // proxy models
    m_sortFilter = new QSortFilterProxyModel(this);
    m_sortFilter->setSourceModel(m_specialsSelect);


    // item views
    ui->tableView->setModel(m_specialTable);
    ui->listView->setModel(m_sortFilter);

    QItemSelectionModel* selectModel = ui->tableView->selectionModel();
    connect(selectModel, &QItemSelectionModel::selectionChanged, this, &CharacterSpecialsForm::onSectionChanged);

    connect(ui->tableView->model(), &QAbstractItemModel::dataChanged, this, &CharacterSpecialsForm::onSpecialChanged);
    connect(ui->listView->model(), &QAbstractItemModel::dataChanged, this, &CharacterSpecialsForm::onSpecialChanged);

    // delegates
    ui->tableView->setItemDelegate(new CharacterSpecialDelegate(this));

    // splitter
    ui->splitter->setStretchFactor(0,2);
    ui->splitter->setStretchFactor(1,0);


    // initial states
    ui->tabWidget->setCurrentWidget(ui->tabSpecials);
}

CharacterSpecialsForm::~CharacterSpecialsForm()
{
    delete ui;
}

void CharacterSpecialsForm::setCampaign(Campaign *campaign)
{
    m_specialTable->setCampaign(campaign);
    m_specialsSelect->setCampaign(campaign);

    ui->tableView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->listView->model()->sort(0);
}

void CharacterSpecialsForm::addSpecialAbility()
{
    int rows = m_sortFilter->rowCount();
    m_sortFilter->insertRows(rows, 1);

    QModelIndex source = m_specialsSelect->index(rows);
    QModelIndex proxy = m_sortFilter->mapFromSource(source);

    if (!proxy.isValid())
    {
        qDebug() << Q_FUNC_INFO << "Inserted proxy index is invalid!";
        return;
    }

    ui->listView->setCurrentIndex(proxy);
    ui->listView->scrollTo(proxy);
    ui->listView->edit(proxy);
}

void CharacterSpecialsForm::removeSpecialAbility()
{
    QModelIndex index = ui->listView->currentIndex();
    if (!index.isValid())
    {
        return;
    }

    ui->listView->model()->removeRows(index.row(), 1);

    QTimer::singleShot(0, m_specialTable, SLOT(revert()));
}

void CharacterSpecialsForm::refresh()
{
    m_specialTable->revert();
}

void CharacterSpecialsForm::onSectionChanged()
{
//    qDebug() << Q_FUNC_INFO;
    QModelIndex index = ui->tableView->currentIndex();
    if (!index.isValid())
    {
        qDebug() << "*** Current index is invalid!";
        return;
    }

    QVariant characterClass = index.data(SpecialTableModel::Role_CharacterClass);
    if (!characterClass.isValid())
    {
        qDebug() << "*** Character class name is invalid!";
        return;
    }

    m_specialsSelect->setCharacterClassLevel(characterClass.toString(), index.row());

}

void CharacterSpecialsForm::onSpecialChanged()
{
    if (sender() == ui->tableView->model())
    {
        ui->listView->model()->revert();
        m_specialsSelect->sort(0);
        return;
    }

    m_specialsSelect->sort(0);

    QModelIndex index = ui->tableView->currentIndex();
    ui->tableView->update(index);

    QHeaderView* header = ui->tableView->verticalHeader();
    header->setSectionResizeMode(QHeaderView::ResizeToContents);

}

void CharacterSpecialsForm::onCheckBoxClicked(int id)
{
    QCheckBox* cb = qobject_cast<QCheckBox*>(m_checkboxes->button(id));
    if (!cb)
    {
        return;
    }

    if (cb->isChecked())
    {
        ui->tableView->setColumnHidden(id, false);
        return;
    }

    ui->tableView->setColumnHidden(id, true);
}

void CharacterSpecialsForm::showEvent(QShowEvent *e)
{
    refresh();

    QWidget::showEvent(e);
}


void CharacterSpecialsForm::on_tabWidget_currentChanged(int index)
{
    Q_UNUSED(index)

    if (ui->tabWidget->currentWidget() == ui->tabSpecials)
    {
        return;
    }

    foreach (QAbstractButton* button, m_checkboxes->buttons())
    {
        button->deleteLater();
    }

    int count = ui->tableView->model()->columnCount();
    if (count <= 0)
    {
        qDebug() << Q_FUNC_INFO << "No columns in table view";
    }

    for (int i = 0; i < count; i++)
    {
        QString text = ui->tableView->model()->headerData(i, Qt::Horizontal, SpecialTableModel::Role_CharacterClass).toString();
        if (text.isEmpty())
        {
            text = tr("[nameless]");
        }

        QCheckBox* cb = new QCheckBox(text, ui->tabCharacterClasses);
        m_checkboxes->addButton(cb, i);
        cb->setChecked(!ui->tableView->isColumnHidden(i));
        ui->vlayCharacterClasses->insertWidget(i, cb);
    }
}
